import { ref, reactive, toRaw, onMounted, h } from "vue";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import { vehicleUsageApi } from "@/api/business/vehicleUsage";
import { fuelApi } from "@/api/business/fuel";
import dayjs from "dayjs";
import * as XLSX from "xlsx";
import * as XLSXstyle from "xlsx-style";
const utils = XLSX.utils;

import {
  getKeyList,
  cloneDeep,
  isAllEmpty,
  deviceDetection
} from "@pureadmin/utils";

const exportQueryForm = reactive({
  type: 1,
  timeRange: []
});

const queryPrams = reactive({
  queryStartTime: dayjs().format("YYYY-MM-DD 00:00:00"),
  queryEndTime: dayjs().format("YYYY-MM-DD 23:59:59")
});

const queryFormRef = ref();
// 添加分页参数响应式声明
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});
// 序号计算逻辑
const autoIndex = (index: number) => {
  return (
    index +
    1 +
    ((pagination.currentPage || 1) - 1) * (pagination.pageSize || 10)
  );
};

// 扁平化嵌套列配置，生成多级表头信息
export const flattenColumns = (columns, level = 0, parentPath = "") => {
  const result = [];

  columns.forEach((column, index) => {
    const path = parentPath ? `${parentPath}.${index}` : `${index}`;

    // 如果有子列，递归处理
    if (column.children && column.children.length) {
      result.push({
        ...column,
        level,
        path,
        children: undefined,
        isParent: true,
        childCount: column.children.length
      });

      const children = flattenColumns(column.children, level + 1, path);
      result.push(...children);
    } else {
      // 叶子节点列
      result.push({
        ...column,
        level,
        path,
        isParent: false,
        childCount: 1
      });
    }
  });

  return result;
};

// 处理导出数据，根据列配置转换数据格式
export const processExportData = (dataList, leafColumns) => {
  if (!dataList || !dataList.length) return [];
  return dataList.map((item, index) => {
    const processedItem = {};
    leafColumns.forEach(column => {
      const prop = column.prop;
      if (typeof column.index === "function") {
        processedItem[prop] = autoIndex(index); // 使用遍历的index参数
      }
      if (!prop) return;
      // 如果有单元格渲染函数，使用它处理数据
      if (typeof column.cellRenderer === "function") {
        processedItem[prop] = column.cellRenderer({ row: item }) || "-";
      }
      // 如果有formatter函数，使用它处理数据
      else if (typeof column.formatter === "function") {
        processedItem[prop] = column.formatter(item) || "-";
      } else {
        // 没有渲染函数，直接使用原始值
        processedItem[prop] = item[prop] || "-";
      }
    });
    console.log("processedItem", processedItem);
    return processedItem;
  });
};

// 生成多级表头
export const generateHeaderRows = columns => {
  const flatColumns = flattenColumns(columns);
  const maxLevel = Math.max(...flatColumns.map(col => col.level));
  const headerRows = Array.from({ length: maxLevel + 1 }, () => []);
  console.log("flatColumns", flatColumns);
  console.log("maxLevel", maxLevel);
  console.log("headerRows", headerRows);
  flatColumns.forEach(column => {
    const { level, label, childCount } = column;

    // 在当前层级添加表头
    headerRows[level].push({
      label,
      colspan: childCount,
      rowspan: 1
    });

    // 计算子表头的合并情况
    if (column.isParent) {
      // 精确匹配直接子列，排除孙辈列
      const children = flatColumns.filter(
        child =>
          child.path.startsWith(`${column.path}.`) &&
          child.path.split(".").length === column.path.split(".").length + 1
      );

      // 计算子列的最大层级
      const maxChildLevel = children.length
        ? Math.max(...children.map(child => child.level))
        : level;
      headerRows[level][headerRows[level].length - 1].rowspan =
        maxChildLevel - level + 1;
      headerRows[level][headerRows[level].length - 1].colspan = children.length;
    }
  });
  return headerRows;
};

// 为carTotal类型添加特殊标题
export const addCarTotalTitle = (workSheet, queryPrams) => {
  if (!workSheet["!rows"]) workSheet["!rows"] = [];
  workSheet["!rows"].push({ hpt: 40 });
  // 添加标题单元格样式
  workSheet["!cols"] = [{ width: 20 }, { width: 15 }];
  const cellAddress = XLSX.utils.encode_cell({ c: 0, r: 0 }); // A1
  const titleCell = (workSheet[cellAddress] = workSheet[cellAddress] || {});
  titleCell.s = {
    font: {
      name: "宋体",
      sz: 22,
      bold: true,
      color: { rgb: "000000" }
    },
    alignment: {
      horizontal: "center",
      vertical: "center",
      wrapText: true
    },
    border: {
      top: { style: "thin", color: { rgb: "000000" } },
      bottom: { style: "thin", color: { rgb: "000000" } },
      left: { style: "thin", color: { rgb: "000000" } },
      right: { style: "thin", color: { rgb: "000000" } }
    },
    // 添加可能需要的额外属性
    fill: { fgColor: { rgb: "FFFFFF" } } // 显式设置背景色
  };

  // 获取数据的年份
  const year = dayjs(queryPrams.queryStartTime).format("YYYY");

  // 添加标题行
  const titleRow = [
    {
      v: `${year}年度总局总部及各直属单位(含三级)公务用车统计表`,
      s: { alignment: { horizontal: "center" } }
    }
  ];
  utils.sheet_add_aoa(workSheet, [titleRow], { origin: "A1" });

  // 设置标题行高
  if (!workSheet["!rows"]) workSheet["!rows"] = [];
  workSheet["!rows"].push({ hpt: 40 }); // 设置行高为40点

  // 添加副标题行
  const subtitleRow = [
    { v: "中煤航测遥感集团有限公司", s: { alignment: { horizontal: "left" } } }
  ];
  utils.sheet_add_aoa(workSheet, [subtitleRow], { origin: -1 });
  // 设置副标题行高
  workSheet["!rows"].push({ hpt: 20 }); // 设置行高为20点

  // 计算最后一列索引（新增代码）
  const leafColumns = flattenColumns(workSheet._originalColumns).filter(
    col => !col.isParent
  );
  const lastColIndex = leafColumns.length - 1; // 定义缺失的lastColIndex变量

  // 合并标题单元格，跨越所有列
  if (!workSheet["!merges"]) workSheet["!merges"] = [];

  // 合并标题行（如果需要保留标题合并请取消注释）
  workSheet["!merges"].push({
    s: { r: 0, c: 0 },
    e: { r: 0, c: lastColIndex }
  });

  // 合并副标题行（如果需要保留副标题合并请取消注释）
  workSheet["!merges"].push({
    s: { r: 1, c: 0 },
    e: { r: 1, c: lastColIndex }
  });

  // 保存原始列配置，用于计算合并单元格
  if (!workSheet._originalColumns) {
    workSheet._originalColumns = workSheet._originalColumns || [];
  }
};
// 导出Excel核心函数
export const exportExcel = async (
  dataList: any[],
  columns: TableColumnList,
  type: string,
  queryPrams: Record<string, any> = {}
) => {
  if (!dataList || !dataList.length) {
    message("暂无数据可导出", { type: "warning" });
    return;
  }

  // 临时处理
  if (type === "carTotal") {
    columns.forEach((column, index) => {
      if (column.children && column.children.length) {
        const newChild = column.children;
        columns.splice(index, 1, ...newChild);
      }
    });
  }

  // 过滤掉隐藏列、操作列
  const visibleColumns = columns.filter(
    col => !col.hide && col.slot !== "operation"
  );

  // // 跳过隐藏列、操作列
  // if (column.hide || column.slot == "operation") return;
  console.log("过滤掉隐藏列、操作列", visibleColumns);
  // 扁平化列配置，获取所有叶子节点列
  const flatColumns = flattenColumns(visibleColumns);
  const leafColumns = flatColumns.filter(col => !col.isParent);
  // 处理数据，应用列配置中的渲染函数
  const processedData = processExportData(dataList, leafColumns);

  // 创建工作表
  const workSheet = utils.aoa_to_sheet([]);
  const workBook = XLSX.utils.book_new(); // 创建工作簿
  // 保存原始列配置，用于计算合并单元格
  workSheet._originalColumns = visibleColumns;

  // 为carTotal类型添加特殊标题
  if (type === "carTotal") {
    addCarTotalTitle(workSheet, queryPrams);
  }

  // 生成多级表头
  const headerRows = generateHeaderRows(visibleColumns).filter(row =>
    // 只保留包含有效单元格的行
    row.some(cell => cell.label || cell.colspan > 1 || cell.rowspan > 1)
  );
  console.log("生成多级表头", headerRows);
  console.log("过滤后的表头行数:", headerRows.length); // 验证表头行数
  // 添加多级表头
  headerRows.forEach((row, rowIndex) => {
    const rowData = row.map(cell => ({ v: cell.label, t: "s" }));
    if (type === "carTotal") {
      utils.sheet_add_aoa(workSheet, [rowData], { origin: -1 }); //-1 表示追加到工作表末尾
    } else {
      utils.sheet_add_aoa(workSheet, [rowData], { origin: "A1" }); // A1表示从第一行第一列开始插入
    }
    let currentColIndex = 0;
    // 设置合并单元格
    row.forEach((cell, colIndex) => {
      // 仅处理需要合并的单元格（列合并或行合并）
      if (cell.colspan > 1 || cell.rowspan > 1) {
        // 初始化合并区域数组（如不存在）
        if (!workSheet["!merges"]) workSheet["!merges"] = [];

        // 计算实际行索引（考虑前面可能添加的标题行）
        const titleRowOffset = type === "carTotal" ? 2 : 0;
        const actualRowIndex = rowIndex + titleRowOffset;
        // 添加合并区域定义
        workSheet["!merges"].push({
          s: { r: actualRowIndex, c: currentColIndex }, // 使用累积列索引
          e: {
            r: actualRowIndex + cell.rowspan - 1,
            c: currentColIndex + cell.colspan - 1
          }
        });
      }
      // 无论是否合并单元格，都更新列索引
      currentColIndex += cell.colspan || 1;
      console.log(`行${rowIndex}列索引:`, currentColIndex);
    });
  });

  // 添加数据前过滤空行
  const dataRows = processedData
    .filter(item =>
      Object.values(item).some(v => v !== null && v !== undefined && v !== "")
    )
    .map(item => {
      return leafColumns.map(column => ({
        v: item[column.prop] || "",
        t: "s"
      }));
    });
  console.log("添加数据", dataRows);
  utils.sheet_add_aoa(workSheet, dataRows, { origin: -1 });
  XLSX.utils.book_append_sheet(workBook, workSheet, "统计报表"); // 添加工作表

  // 设置列宽
  const columnWidths = leafColumns.map(col => ({
    wch: (col.width || 100) / 7
  }));
  workSheet["!cols"] = columnWidths;

  const title = {
    carTotal: "用车统计记录",
    oil: "加油报表统计记录",
    car: "用车报表统计记录"
  };

  console.log("表头结构:", JSON.stringify(headerRows, null, 2));
  console.log("合并区域:", JSON.stringify(workSheet["!merges"], null, 2));
  const fileName = `${dayjs(queryPrams.queryStartTime).format("YYYY-MM-DD")}至${dayjs(queryPrams.queryEndTime).format("YYYY-MM-DD")}${title[type]}.xlsx`;
  // XLSX.writeFile(workBook, fileName);
  const wbout = XLSX.write(workBook, {
    bookType: "xlsx",
    type: "buffer",
    cellStyles: true
  });
  // 浏览器下载逻辑;
  const blob = new Blob([wbout], { type: "application/octet-stream" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  // 清理资源
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 100);
  message("导出成功", { type: "success" });
};

// 导出对话框打开函数（需通过参数传递依赖的状态）
export const openExportDialog = (
  column: TableColumnList,
  type: string,
  tableData?: any
) => {
  addDialog({
    title: `选择时间段`,
    width: "40%",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => (
      <div style="padding: 20px; height: 100%; overflow-y: auto">
        <el-form ref={queryFormRef} model={exportQueryForm} label-width="100px">
          <el-form-item label="时间范围" prop="timeRange">
            <el-radio-group
              modelValue={exportQueryForm.type}
              onUpdate:modelValue={val => (exportQueryForm.type = val)}
            >
              <el-radio-button label="customTime" value={1}>
                今天
              </el-radio-button>
              <el-radio-button label="thisWeek" value={7}>
                本周
              </el-radio-button>
              <el-radio-button label="thisMonth" value={30}>
                近30天
              </el-radio-button>
              <el-radio-button label="thisMonth" value={0}>
                自定义
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          {exportQueryForm.type === 0 && (
            <el-form-item label="选择开始范围" prop="timeRange">
              <el-date-picker
                modelValue={exportQueryForm.timeRange}
                onUpdate:modelValue={val => (exportQueryForm.timeRange = val)}
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                placeholder="选择开始范围"
              />
            </el-form-item>
          )}
        </el-form>
      </div>
    ),
    beforeSure: async (done, { options }) => {
      if (exportQueryForm.type === 1) {
        queryPrams.queryStartTime = dayjs().format("YYYY-MM-DD 00:00:00");
        queryPrams.queryEndTime = dayjs().format("YYYY-MM-DD 23:59:59");
      } else if (exportQueryForm.type === 7) {
        queryPrams.queryStartTime = dayjs()
          .startOf("week")
          .format("YYYY-MM-DD HH:mm:ss");
        queryPrams.queryEndTime = dayjs()
          .endOf("day")
          .format("YYYY-MM-DD 23:59:59");
      } else if (exportQueryForm.type === 30) {
        queryPrams.queryStartTime = dayjs()
          .subtract(30, "days")
          .format("YYYY-MM-DD 00:00:00");
        queryPrams.queryEndTime = dayjs()
          .subtract(1, "days")
          .format("YYYY-MM-DD 23:59:59");
      } else {
        queryPrams.queryStartTime = exportQueryForm.timeRange[0];
        queryPrams.queryEndTime = exportQueryForm.timeRange[1];
      }

      let curData = [];
      let result;

      switch (type) {
        case "car":
          result = await vehicleUsageApi.getListByGets(queryPrams);
          break;
        case "oil":
          result = await fuelApi.getFuelLists(queryPrams);
          break;
        case "totalCar":
          result = await vehicleUsageApi.getVehicleReport(toRaw(queryPrams));
          break;
      }

      console.log(result);

      if (result?.success) {
        curData = result.data || [];
        pagination.total = result.total;
        pagination.currentPage = result.pageNum;
        pagination.pageSize = result.pageSize;
        if (!curData.length) {
          message("暂无数据可导出", { type: "warning" });
          return;
        }

        // 校验表单后执行导出
        queryFormRef.value.validate(async valid => {
          if (valid) {
            await exportExcel(curData, column, type, queryPrams);
            await done();
          } else {
            message("表单验证失败", { type: "warning" });
          }
        });
      } else {
        message(result?.message || "导出失败", { type: "warning" });
      }
    }
  });
};
